package service.impl;

import dao.SeckillDao;
import dao.impl.SeckillDaoImpl;
import exception.SecKillException;
import model.Seckill;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import service.SeckillService;
import utils.JedisPoolUtil;

import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author one world
 * @Date 2020/9/22 0022 18:43
 */
public class SeckillServiceImpl implements SeckillService {
    SeckillDao dao = new SeckillDaoImpl();

    @Override
    public List<Seckill> findAll(int page,int limit) {
        return dao.findAll(page,limit);
    }

    @Override
    public List<Seckill> findAll(){
        return dao.findAll();
    }

    @Override
    public int findCount() {
        return dao.findCount();
    }

    @Override
    public Seckill findById(Integer id) {
        return dao.findByPK(id);
    }

    @Override
    public boolean add(Seckill seckill) {
        return dao.add(seckill);
    }

    @Override
    public boolean update(Seckill seckill) {
        return dao.update(seckill);
    }

    @Override
    public boolean del(Integer id) {
        return dao.delByPK(id);
    }

    @Override
    public boolean startSecKill() {
        Jedis jedis = JedisPoolUtil.getJedis();
        List<Seckill> seckills = dao.findAll();
        for (Seckill seckill : seckills) {
            for (int i = 0; i < seckill.getStotal(); i++) {
                jedis.rpush("seckill:count:" + seckill.getId(), String.valueOf(seckill.getGoods().getId()));
            }
        }
        return true;
    }

    @Override
    public void secKill(Integer user_id, Integer seckill_id, Integer num) throws SecKillException {
        Jedis jedis = JedisPoolUtil.getJedis();
        Seckill seckill = findById(seckill_id);
        Integer state = seckill.getState();
        if (state == 0) {
            throw new SecKillException("秒杀还未开始！");
        }
        //日期类的比较compareTo()方法,若前一个小于后日期时，为负数，相等时等于0，大于时，为正数
        if (state == 2 || seckill.getStotal() == 0 || seckill.getEnd_time().compareTo(new Date()) < 0) {
            throw new SecKillException("秒杀已结束！");
        }
        String goodsIdStr = jedis.lpop("seckill:count:" + seckill_id);
        //存放商品
        Integer goodsId = 0;
        if (goodsIdStr == null || goodsIdStr.equals("") ||goodsIdStr.equals("null")) {
            seckill.setState(2);
            update(seckill);
            throw new SecKillException("该商品已抢光！");
        } else {
            goodsId = Integer.parseInt(goodsIdStr);
            //判断该用户是否已经抢过该商品了
            boolean flag = jedis.sismember("seckill:users:"+seckill_id,String.valueOf(user_id));
            if(!flag){
                jedis.sadd("seckill:users:"+seckill_id,String.valueOf(user_id));
            }else{
                jedis.rpush("seckill:count:"+seckill_id,String.valueOf(seckill.getGoods().getId()));
                throw new SecKillException("别太贪心哦！");
            }
        }

    }

}
